﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using EkStudio.com.bean.xml.BillMapping;
using EkStudio.com.bean.xml.BillModule;
using EkStudio.com.bean.xml.ProjectMenu;
using EkStudio.com.bean.xml.reflection.JAXB;
using EkStudio.com.bean.xml.RootInterface.Field;
using EkStudio.com.bean.xml.Unit;
using EkStudio.com.common.unit;
using EkStudio.com.ui.unitbill;
using EkStudio.com.ui.unitbill.property.Event;
using ScintillaNET;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace EkStudio.com.ui.form.MapDataSource
{
    public partial class MapGroupClassForm : XtraForm
    {

        private ProjectRootPanel RootPanel = null;
        private BillMapUnitPanel UnitPanel = null;

        private BillDataMapItem Map = null;

        private BillDataMapGroupItem group = null;

        private int mainThreadId = -1;

        private BillModuleItem bill = null;

        private List<FieldSelectItem> fieldList = new List<FieldSelectItem>();

        private DataTable groupby = null,stock = null;

        public MapGroupClassForm(ProjectRootPanel root,BillMapUnitPanel unit,BillDataMapItem bean)
        {
            InitializeComponent();
            RootPanel = root;
            UnitPanel = unit;
            Map = bean;
            InitForm();
        }

        private void InitForm()
        {

            #region 初始化编辑器
            this.SqlEdit.Margins[0].Width = 20;
            this.SqlEdit.Margins[2].Type = MarginType.Symbol;
            this.SqlEdit.Margins[2].Mask = Marker.MaskFolders;
            this.SqlEdit.Margins[2].Sensitive = true;
            this.SqlEdit.Margins[2].Width = 20;

            SqlEdit.Markers[Marker.Folder].Symbol = MarkerSymbol.BoxPlus;
            SqlEdit.Markers[Marker.FolderOpen].Symbol = MarkerSymbol.BoxMinus;
            SqlEdit.Markers[Marker.FolderEnd].Symbol = MarkerSymbol.BoxPlusConnected;
            SqlEdit.Markers[Marker.FolderMidTail].Symbol = MarkerSymbol.TCorner;
            SqlEdit.Markers[Marker.FolderOpenMid].Symbol = MarkerSymbol.BoxMinusConnected;
            SqlEdit.Markers[Marker.FolderSub].Symbol = MarkerSymbol.VLine;
            SqlEdit.Markers[Marker.FolderTail].Symbol = MarkerSymbol.LCorner;

            SqlEdit.StyleResetDefault();
            SqlEdit.Styles[Style.Default].Font = "Consolas";
            SqlEdit.Styles[Style.Default].Size = 10;
            SqlEdit.StyleClearAll();


            // Configure the CPP (C#) lexer styles
            SqlEdit.Styles[Style.Cpp.Default].ForeColor = Color.Silver;
            SqlEdit.Styles[Style.Cpp.Comment].ForeColor = Color.FromArgb(0, 128, 0); // Green
            SqlEdit.Styles[Style.Cpp.CommentLine].ForeColor = Color.FromArgb(0, 128, 0); // Green
            SqlEdit.Styles[Style.Cpp.CommentLineDoc].ForeColor = Color.FromArgb(128, 128, 128); // Gray
            SqlEdit.Styles[Style.Cpp.Number].ForeColor = Color.Olive;
            SqlEdit.Styles[Style.Cpp.Word].ForeColor = Color.Blue;
            SqlEdit.Styles[Style.Cpp.Word2].ForeColor = Color.Blue;
            SqlEdit.Styles[Style.Cpp.String].ForeColor = Color.FromArgb(163, 21, 21); // Red
            SqlEdit.Styles[Style.Cpp.Character].ForeColor = Color.FromArgb(163, 21, 21); // Red
            SqlEdit.Styles[Style.Cpp.Verbatim].ForeColor = Color.FromArgb(163, 21, 21); // Red
            SqlEdit.Styles[Style.Cpp.StringEol].BackColor = Color.Pink;
            SqlEdit.Styles[Style.Cpp.Operator].ForeColor = Color.Purple;
            SqlEdit.Styles[Style.Cpp.Preprocessor].ForeColor = Color.Maroon;
            SqlEdit.Lexer = Lexer.Cpp;

            // Set the keywords
            //SqlEdit.SetKeywords(0, "abstract as base break case catch checked continue default delegate do else event explicit extern false finally fixed for foreach goto if implicit in interface internal is lock namespace new null object operator out override params private protected public readonly ref return sealed sizeof stackalloc switch this throw true try typeof unchecked unsafe using virtual while");
            //SqlEdit.SetKeywords(1, "bool byte char class const decimal double enum float int long sbyte short static string struct uint ulong ushort void");

            SqlEdit.SetKeywords(0, ULabel.SQLKeys);

            #endregion

            mainThreadId = Thread.CurrentThread.ManagedThreadId;
            //初始化目录列表
            if (RootPanel.MenuItem != null && RootPanel.MenuItem.Business != null
                && RootPanel.MenuItem.Business.Modules != null && RootPanel.MenuItem.Business.Modules.Count > 0)
            {
                ImageComboBoxItem select = new ImageComboBoxItem("请选择单据...", null, 6);
                ModComboBoxEdit.Properties.Items.Add(select);
                foreach (ProjectMenuModGroup mod in RootPanel.MenuItem.Business.Modules)
                {
                    if (mod.Module != null && mod.Module.Count > 0)
                    {
                        foreach (ProjectMenuCommonElement it in mod.Module)
                        {
                            ImageComboBoxItem item = new ImageComboBoxItem(it.Caption, it, 6);
                            ModComboBoxEdit.Properties.Items.Add(item);
                        }
                    }
                }
            }
            groupby = new DataTable("GroupByTable");
            groupby.Columns.Add("GroupCaption",typeof(string));
            groupby.Columns.Add("Groupkey", typeof(string));
            groupby.Columns.Add("GroupSource", typeof(string));
            groupby.Columns.Add("FieldCaption", typeof(string));
            groupby.Columns.Add("FieldKey", typeof(string));
            groupby.Columns.Add("FieldSource", typeof(string));
            GridGroupControl.DataSource = groupby;

            stock = new DataTable("StockByTable");
            stock.Columns.Add("GroupCaption", typeof(string));
            stock.Columns.Add("Groupkey", typeof(string));
            stock.Columns.Add("GroupType", typeof(string));
            stock.Columns.Add("FieldCaption", typeof(string));
            stock.Columns.Add("FieldKey", typeof(string));
            stock.Columns.Add("FieldSource", typeof(string));

            GridNumberControl.DataSource = stock;

        }


        public BillDataMapGroupItem Group
        {
            get { return group; }
            set
            {
                group = value;
                LoadGroupItem();
            }
        }

        /// <summary>
        /// 加载Group时执行
        /// </summary>
        public void LoadGroupItem()
        {
            LoadTimer.Enabled = true;
            if (group.Field == null) group.Field = new List<BillDataMapField>();
            //出入类型 红字 蓝字
            toggleSwitchStock.IsOn = group.GroupType == BeanUtil.STOCK_GROUP_ST_BLUE;
            //影响类型
            if(group.StockType == BeanUtil.STOCK_GROUP_ST_INTO_STOCK)
            {
                StockComboBoxEdit.SelectedIndex = 0;
            }else if(group.StockType == BeanUtil.STOCK_GROUP_ST_OUT_STOCK)
            {
                StockComboBoxEdit.SelectedIndex = 1;
            }
            else
            {
                StockComboBoxEdit.SelectedIndex = 2;
            }
            //状态字段
            if (group.StatusKey != "")
                StautsComboBox.SelectedItem = group.StatusCaption;
            //日期字段
            if (group.DateKey != "") DateComboBox.SelectedItem = group.DateCaption;

            //选择模块对象
            if (group.TargetKey == "")
            {
                ModComboBoxEdit.SelectedIndex = 0;
            }
            else
            {
                foreach(ImageComboBoxItem box in ModComboBoxEdit.Properties.Items)
                {
                    if(box.Value is ProjectMenuCommonElement)
                    {
                        ProjectMenuCommonElement ele = box.Value as ProjectMenuCommonElement;
                        if(ele.Command == group.TargetKey)
                        {
                            ModComboBoxEdit.SelectedItem = box;
                            break;
                        }
                    }
                }
            }
            //初始分组字段列表
            groupby.Rows.Clear();
            if(Map.MapProperties.Advanced!=null&&Map.MapProperties.Advanced.Field!=null
                && Map.MapProperties.Advanced.Field.Count > 0)
            {
                foreach(BillDataMapAdvancedElement adIt in Map.MapProperties.Advanced.Field)
                {
                    if(adIt.Command == BeanUtil.MAP_STGROUP)
                    {
                        DataRow row = groupby.NewRow();
                        row["GroupCaption"] = adIt.Caption;
                        row["Groupkey"] = adIt.Key;
                        row["GroupSource"] = adIt.DataSource;
                        row["FieldCaption"] = "";
                        row["FieldKey"] = "";
                        row["FieldSource"] = "";

                        if (group.Field != null && group.Field.Count > 0)
                        {
                            foreach(BillDataMapField field in group.Field)
                            {
                                if(field.Linker == adIt.Key)
                                {
                                    row["FieldCaption"] = field.Caption;
                                    row["FieldKey"] = field.Key;
                                    row["FieldSource"] = field.DataSource;
                                }
                            }
                        }
                        groupby.Rows.Add(row);
                    }
                    
                }
            }
            //初始结存对象
            stock.Rows.Clear();
            if(Map.MapProperties.Target!=null&&Map.MapProperties.Target.Element!=null
                && Map.MapProperties.Target.Element.Count > 0)
            {
                foreach(BillDataMapTargetElement tg in Map.MapProperties.Target.Element)
                {
                    if(tg.NodeType == BeanUtil.STOCK_MAP_FIELD_SUMMARY || tg.NodeType == BeanUtil.STOCK_MAP_FIELD_MONEY)
                    {
                        DataRow row = stock.NewRow();
                        row["GroupCaption"] = tg.Caption;
                        row["Groupkey"] = tg.Key;
                        row["GroupType"] = tg.NodeType;
                        row["FieldCaption"] = "";
                        row["FieldKey"] = "";
                        row["FieldSource"] = "";

                        if (group.Field != null && group.Field.Count > 0)
                        {
                            foreach (BillDataMapField field in group.Field)
                            {
                                if (field.Linker == tg.Key && field.LinkerType == BeanUtil.MAP_STNUMBER)
                                {
                                    row["FieldCaption"] = field.Caption;
                                    row["FieldKey"] = field.Key;
                                    row["FieldSource"] = field.DataSource;
                                }
                            }
                        }
                        stock.Rows.Add(row);
                    }
                }
            }

            SqlEdit.Text = group.Content;
            CheckStockNumber.Checked = group.ValidateStock;
        }
        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadBill()
        {
            if (ModComboBoxEdit.SelectedItem != null && (ModComboBoxEdit.SelectedItem as ImageComboBoxItem).Value != null)
            {
                ImageComboBoxItem select = ModComboBoxEdit.SelectedItem as ImageComboBoxItem;
                if (select.Value is ProjectMenuCommonElement)
                {
                    ProjectMenuCommonElement ele = select.Value as ProjectMenuCommonElement;
                    ProgressBarControl.Visible = true;
                    bool read = false;//不验证数据
                    RootPanel.Http.AsyncResourcesXmlBean(ele.Command, ele.Caption, ProjectUtil.TYPE_BILL_MODULE, ref read, null, ThreadLoadXml);
                }
            }
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ThreadLoadXml(object sender, PropertyDataEvent e)
        {
            
            if (Thread.CurrentThread.ManagedThreadId != mainThreadId)
            {
                BeginInvoke(new KEventHandler(ThreadLoadXml), new object[] { sender, e });
            }
            else
            {
                bool success = false;
                if (e.Key == "OK")//加载成功
                {
                    string xml = e.Value as string;
                    JAXBContext<BillModuleItem> jaxb = new JAXBContext<BillModuleItem>();
                    try
                    {
                        bill = jaxb.unmarshal(xml);
                        success = true;
                    }
                    catch (Exception ee)
                    {
                        RootPanel.AddConsoleText(ee.Message, true);
                    }
                    if (bill == null)
                    {
                        RootPanel.ShowAlert("提示", "xml解析失败");
                    }
                }
                else
                {
                    RootPanel.ShowAlert("提示", "加载配置异常:" + e.Value.ToString());
                }

                if (success)
                {
                    FinisLoad();
                }
                else
                {
                    Text = "库存对象设置";
                }

                ProgressBarControl.Visible = false;
            }
        }
        /// <summary>
        /// 模块数据加载完成后执行
        /// </summary>
        private void FinisLoad()
        {
            Text = string.Format("分组对象设置-{0}", bill.getCaption());
            SheetComboBox.Properties.Items.Clear();
            SheetComboBox.Properties.Items.Add("");
            //初始化子表下拉框内容
            if (bill.UiField != null && bill.UiField.FieldsProperties != null
                && bill.UiField.FieldsProperties.Count > 0)
            {
                foreach (BillUiGroupItems gIt in bill.UiField.FieldsProperties)
                {
                    if (gIt.Table)
                    {
                        SheetComboBox.Properties.Items.Add(gIt.TableName);
                    }
                }
            }
            //选中默认的子表
            if(SheetComboBox.Properties.Items.Count > 1)
            {
                if (group.TargetSheet != "" && group.TargetKey == bill.getKey())
                {
                    SheetComboBox.SelectedText = group.TargetSheet;
                }
                else
                {
                    SheetComboBox.SelectedIndex = 1;
                }
            }
            else
            {
                SheetComboBox.SelectedIndex = 0;
            }
        }
        /// <summary>
        /// 初始化模块信息
        /// </summary>
        private void ReadyList()
        {
            fieldList.Clear();
            string caption = "";
            if(SheetComboBox.SelectedIndex > 0)
            {
                caption = SheetComboBox.SelectedItem.ToString() ;
            }
            //初始化所有下拉框内容
            StautsComboBox.Properties.Items.Clear(); StautsComboBox.Properties.Items.Add("");
            DateComboBox.Properties.Items.Clear();DateComboBox.Properties.Items.Add("");
            KeyComboBox.Properties.Items.Clear();KeyComboBox.Properties.Items.Add("");
            RepositoryGroupList.Items.Clear(); RepositoryGroupList.Items.Add("");
            RepositoryNumberList.Items.Clear(); RepositoryNumberList.Items.Add("");
            if (bill.UiField != null && bill.UiField.FieldsProperties != null
                && bill.UiField.FieldsProperties.Count > 0)
            {
                foreach (BillUiGroupItems gIt in bill.UiField.FieldsProperties)
                {
                    if (gIt.Fields != null && gIt.Fields.Count > 0)
                    {
                        if (!gIt.Table)
                        {
                            foreach (BillUiFieldsItem field in gIt.Fields)
                            {
                                if(field.EditProperty.Enable && field.DataProperty.DataSource != "")
                                {
                                    StringBuilder temp = new StringBuilder();
                                    temp.Append(bill.getCaption()).Append(".").Append(field.Caption);
                                    FieldSelectItem item = new FieldSelectItem(field.Key, temp.ToString(), field.DataProperty.DataType, field.DataProperty.DataSource, field.LanguageTexts);
                                    fieldList.Add(item);
                                    if (field.DataProperty.DataType == BeanUtil.KT_DTSTRING)
                                    {
                                        StautsComboBox.Properties.Items.Add(temp.ToString());
                                        RepositoryGroupList.Items.Add(temp.ToString());
                                        KeyComboBox.Properties.Items.Add(temp.ToString());
                                    }
                                    else if(field.DataProperty.DataType == BeanUtil.KT_DTDATETIME)
                                    {
                                        DateComboBox.Properties.Items.Add(temp.ToString());
                                    }
                                    else if(field.DataProperty.DataType == BeanUtil.KT_DTFLOAT 
                                        || field.DataProperty.DataType == BeanUtil.KT_DTINTEGER)
                                    {
                                        RepositoryNumberList.Items.Add(temp.ToString());
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (gIt.TableName == caption)
                            {
                                foreach (BillUiFieldsItem field in gIt.Fields)
                                {
                                    if (field.EditProperty.Enable && field.DataProperty.DataSource !="")
                                    {
                                        StringBuilder temp = new StringBuilder();
                                        temp.Append(bill.getCaption()).Append(".").Append(gIt.Caption).Append(".");
                                        temp.Append(field.Caption);
                                        FieldSelectItem item = new FieldSelectItem(field.Key, temp.ToString(), field.DataProperty.DataType, field.DataProperty.DataSource, field.LanguageTexts);
                                        fieldList.Add(item);
                                        if (field.DataProperty.DataType == BeanUtil.KT_DTSTRING)
                                        {
                                            RepositoryGroupList.Items.Add(temp.ToString());
                                            KeyComboBox.Properties.Items.Add(temp.ToString());
                                        }
                                        else if (field.DataProperty.DataType == BeanUtil.KT_DTFLOAT
                                            || field.DataProperty.DataType == BeanUtil.KT_DTINTEGER)
                                        {
                                            RepositoryNumberList.Items.Add(temp.ToString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //********************重新初始化数据**************************************************
            //1、更新状态控件
            if(group.TargetKey != bill.getKey())
            {
                StautsComboBox.SelectedIndex = 0;
                DateComboBox.SelectedIndex = 0;
                KeyComboBox.SelectedIndex = 0;
            }
            else
            {
                StautsComboBox.SelectedItem = group.StatusCaption;
                DateComboBox.SelectedItem = group.DateCaption;
                KeyComboBox.SelectedItem = group.KeyFieldCaption;

            }
            //2、更新分组列表及数据列表
            if (groupby.Rows.Count > 0)
            {
                foreach(DataRow row in groupby.Rows)
                {
                    string fieldCaption = (string)row["FieldCaption"];
                    bool exists = false;
                    foreach(FieldSelectItem field in fieldList)
                    {
                        if(field.Caption == fieldCaption)
                        {
                            exists = true;
                            break;
                        }
                    }
                    if (!exists)
                    {
                        row["FieldCaption"] = "";
                        row["FieldKey"] = "";
                        row["FieldSource"] = "";
                    }
                }
                GridGroupView.RefreshData();
            }
            //3、更新数据列表
            if (stock.Rows.Count > 0)
            {
                foreach (DataRow row in stock.Rows)
                {
                    string fieldCaption = (string)row["FieldCaption"];
                    bool exists = false;
                    foreach (FieldSelectItem field in fieldList)
                    {
                        if (field.Caption == fieldCaption)
                        {
                            exists = true;
                            break;
                        }
                    }
                    if (!exists)
                    {
                        row["FieldCaption"] = "";
                        row["FieldKey"] = "";
                        row["FieldSource"] = "";
                    }
                }
                GridNumberView.RefreshData();
            }

        }

        new public DialogResult ShowDialog()
        {
            MainTabControl.SelectedTabPageIndex = 0;
            return base.ShowDialog();
        }


        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSubmit_Click(object sender, EventArgs e)
        {
            if(bill == null)
            {
                RootPanel.ShowAlert("提示", "请先选择分组模块对象");
                return;
            }

            if(DateComboBox.SelectedItem.ToString() == "")
            {
                RootPanel.ShowAlert("提示", "请先选择日期映射字段");
                return;
            }

            if (StautsComboBox.SelectedItem.ToString() == "")
            {
                RootPanel.ShowAlert("提示", "请先选择状态映射字段");
                return;
            }

            if (KeyComboBox.SelectedItem.ToString() == "")
            {
                RootPanel.ShowAlert("提示", "请先选择关键映射字段");
                return;
            }
            //验证分组字段
            foreach (DataRow row in groupby.Rows)
            {
                if(((string)row["FieldCaption"]) == "")
                {
                    RootPanel.ShowAlert("提示", string.Format("请先选择分组映射字段[{0}]", (string)row["GroupCaption"]));
                    return;
                }
            }

            foreach (DataRow row in stock.Rows)
            {
                if (((string)row["FieldCaption"]) == "")
                {
                    RootPanel.ShowAlert("提示", string.Format("请先选择库存映射字段[{0}]", (string)row["GroupCaption"]));
                    return;
                }
            }

            if(SqlEdit.Text == "")
            {
                RootPanel.ShowAlert("提示", "请创建SQL语句");
                return;
            }


            group.Field.Clear();
            //变更分组的出库或者入库状态
            group.GroupType = toggleSwitchStock.IsOn ? BeanUtil.STOCK_GROUP_ST_BLUE : BeanUtil.STOCK_GROUP_ST_RED;
            //变量库存分组类型
            if(StockComboBoxEdit.SelectedIndex == 0)
            {
                group.StockType = BeanUtil.STOCK_GROUP_ST_INTO_STOCK;
            }
            else if(StockComboBoxEdit.SelectedIndex == 1)
            {
                group.StockType = BeanUtil.STOCK_GROUP_ST_OUT_STOCK;
            }
            else
            {
                group.StockType = BeanUtil.STOCK_GROUP_ST_LAST_STOCK;
            }
            //保存子表选择
            group.TargetSheet = SheetComboBox.SelectedItem.ToString();
            group.TargetCaption = bill.getCaption();
            group.TargetKey = bill.getKey();
            group.TargetSheet = SheetComboBox.SelectedText;

            //状态字段
            string caption = StautsComboBox.SelectedItem.ToString();
            group.StatusCaption = ""; group.StatusKey = ""; group.StatusSource = "";
            foreach (FieldSelectItem field in fieldList)
            {
                if (field.Caption == caption)
                {
                    group.StatusCaption = field.Caption;
                    group.StatusKey = field.Key;
                    group.StatusSource = field.DataSource;
                    break;
                }
            }
            //关键字段
            caption = KeyComboBox.SelectedItem.ToString();
            group.KeyFieldCaption = ""; group.KeyFieldLanguage = "";
            if ("" != caption)
            {
                foreach (FieldSelectItem field in fieldList)
                {
                    if (field.Caption == caption)
                    {
                        group.KeyFieldCaption = field.Caption;
                        group.KeyFieldLanguage = field.LanguageTexts;
                        break;
                    }
                }
            }

            //日期字段
            caption = DateComboBox.SelectedItem.ToString();
            group.DateCaption = ""; group.DateKey = ""; group.DateSource = "";
            foreach (FieldSelectItem field in fieldList)
            {
                if (field.Caption == caption)
                {
                    group.DateCaption = field.Caption;
                    group.DateKey = field.Key;
                    group.DateSource = field.DataSource;
                    break;
                }
            }

            //保存分组内容
            if (groupby.Rows.Count > 0)
            {
                foreach (DataRow row in groupby.Rows)
                {
                    BillDataMapField item = new BillDataMapField();
                    item.LinkerCaption = (string)row["GroupCaption"];
                    item.Linker = (string)row["Groupkey"];
                    item.LinkerSource = (string)row["GroupSource"];
                    item.LinkerType = BeanUtil.MAP_STGROUP;
                    item.Caption = (string)row["FieldCaption"];
                    item.Key = (string)row["FieldKey"];
                    item.DataSource = (string)row["FieldSource"];
                    if (item.Caption != "")
                    {
                        group.Field.Add(item);
                    }
                }
            }
            //保存计算数据
            if (stock.Rows.Count > 0)
            {
                foreach (DataRow row in stock.Rows)
                {
                    if (!row["FieldCaption"].Equals(""))
                    {
                        BillDataMapField item = new BillDataMapField();
                        item.LinkerCaption = (string)row["GroupCaption"];
                        item.Linker = (string)row["GroupKey"];
                        item.LinkerSource = "";
                        item.Caption = (string)row["FieldCaption"];
                        item.Key = (string)row["FieldKey"];
                        item.DataSource = (string)row["FieldSource"];
                        item.LinkerType = BeanUtil.MAP_STNUMBER;
                        if (item.Caption != "")
                        {
                            group.Field.Add(item);
                        }
                    }
                }
            }

            //保存SQL
            group.Content = SqlEdit.Text;
            //验证状态
            group.ValidateStock = CheckStockNumber.Checked;

            DialogResult = DialogResult.OK;
            Close();
        }

        /// <summary>
        /// 模块选择变更
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ModComboBoxEdit_SelectedValueChanged(object sender, System.EventArgs e)
        {
            if (LoadTimer.Enabled) return;
            if (bill != null && (ModComboBoxEdit.SelectedItem as ImageComboBoxItem).Description != bill.getCaption())
            {
                if (XtraMessageBox.Show("您确认修改目标库存对象吗？如果修改现有配置会被清空", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                {
                    bill = null;
                    LoadBill();
                }
                else
                {
                    foreach (ImageComboBoxItem it in ModComboBoxEdit.Properties.Items)
                    {
                        ProjectMenuCommonElement ele = it.Value as ProjectMenuCommonElement;
                        if (ele != null && ele.Command == bill.getKey())
                        {
                            ModComboBoxEdit.SelectedItem = it;
                            break;
                        }
                    }
                }
            }
            else
            {
                if (bill != null && (ModComboBoxEdit.SelectedItem as ImageComboBoxItem).Description == bill.getCaption())
                {

                }
                else
                {
                    bill = null;
                    LoadBill();
                }
            }

        }

        private void LoadTimer_Tick(object sender, EventArgs e)
        {
            if(bill==null || bill.getKey() != group.TargetKey) LoadBill();
            LoadTimer.Enabled = false;
        }
        /// <summary>
        /// 分组字段选择变更
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridGroupView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if(e.Column.FieldName == "FieldCaption")
            {
                DataRow row = GridGroupView.GetDataRow(e.RowHandle);
                string caption = (string)e.Value;
                foreach(FieldSelectItem field in fieldList)
                {
                    if(field.Caption == caption)
                    {
                        row["FieldKey"] = field.Key;
                        row["FieldSource"] = field.DataSource;
                        break;
                    }
                }
            }
        }

        private void GridNumberView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if(e.Column.FieldName == "FieldCaption")
            {
                DataRow row = GridNumberView.GetDataRow(e.RowHandle);
                string caption = (string)e.Value;
                foreach (FieldSelectItem field in fieldList)
                {
                    if (field.Caption == caption)
                    {
                        row["FieldKey"] = field.Key;
                        row["FieldSource"] = field.DataSource;
                        break;
                    }
                }
            }
        }

        private void BtnAutoSql_Click(object sender, EventArgs e)
        {
            if (bill != null)
            {
                string MainTable = "", SubTable = "";
                if(DateComboBox.SelectedItem.ToString() == "")
                {
                    RootPanel.ShowAlert("提示", "日期字段不可为空");
                    return;
                }
                if (StautsComboBox.SelectedItem.ToString() == "") {
                    RootPanel.ShowAlert("提示", "状态字段不可为空");
                    return;
                }
                //验证分组
                if (groupby.Rows.Count > 0)
                {
                    foreach(DataRow row in groupby.Rows)
                    {
                        if (row["FieldCaption"].Equals(""))
                        {
                            RootPanel.ShowAlert("提示", string.Format("分组字段[{0}]未选择关联字段",(string)row["GroupCaption"]));
                            return;
                        }
                    }
                }
                //验证结存数据
                if (stock.Rows.Count > 0)
                {
                    foreach(DataRow row in stock.Rows)
                    {
                        if (row["FieldCaption"].Equals(""))
                        {
                            RootPanel.ShowAlert("提示", string.Format("库存字段[{0}]未选择关联字段", (string)row["GroupCaption"]));
                            return;
                        }
                    }
                }


                if (bill.DataSource != null && bill.DataSource.TableItems != null && bill.DataSource.TableItems.Count > 0)
                    MainTable = bill.DataSource.TableItems[0].TableName;
                if (!SheetComboBox.SelectedItem.Equals("")) SubTable = SheetComboBox.SelectedItem.ToString();
                if (MainTable != "")
                {
                    if (SubTable != "")
                    {
                        StringBuilder sql = new StringBuilder();
                        sql.Append("select ");
                        //查询日期数据源
                        string statusSource = "", dateSource = "";
                        foreach(FieldSelectItem it in fieldList)
                        {
                            if (statusSource != "" && dateSource != "") break;
                            if(it.Caption == DateComboBox.SelectedItem.ToString())
                            {
                                dateSource = it.DataSource;
                            }else if(it.Caption == StautsComboBox.SelectedItem.ToString())
                            {
                                statusSource = it.DataSource;
                            }
                        }
                        sql.Append(dateSource).Append(",").Append(statusSource);
                        //添加分组字段
                        foreach (DataRow row in groupby.Rows)
                        {
                            sql.Append(",").Append(row["FieldSource"]);
                        }
                        //添加计算字段
                        foreach (DataRow row in stock.Rows)
                        {
                            sql.Append(",SUM(").Append(row["FieldSource"]).Append(") ").Append(row["FieldSource"]);
                        }
                        sql.AppendLine();
                        sql.Append("from ").Append(MainTable).Append(",").Append(SubTable).Append(" ").AppendLine();
                        sql.Append("where ").Append(MainTable).Append(".status=1 and ").Append(SubTable).Append(".status=1").AppendLine();
                        sql.Append("  and ").Append(MainTable).Append(".record_id=").Append(SubTable).Append(".parent_id").AppendLine();
                        sql.Append("  and ").Append(MainTable).Append(".record_id=:ID ").AppendLine();
                        sql.Append("group by ").Append(dateSource).Append(",").Append(statusSource);
                        //添加分组字段
                        foreach (DataRow row in groupby.Rows)
                        {
                            sql.Append(",").Append(row["FieldSource"]);
                        }
                        SqlEdit.Text = sql.ToString();
                    }
                }
            }
            else
            {
                RootPanel.ShowAlert("提示", "请选择单据并配置，最后再进行此操作");
            }
        }

        /// <summary>
        /// 子表选择变更后执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SheetComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (bill != null) ReadyList();
        }
    }
}